package gov.pbc.gx.nn.pz.impl;

import gov.pbc.gx.nn.pz.dao.TcpjjhceqsDao;
import gov.pbc.gx.nn.pz.entity.HcTcpjjhceqs;
import gov.pbc.gx.nn.pz.entity.HcpzXY;
import gov.pbc.gx.nn.pz.entity.PzFont;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.variant.Record;
import com.bstek.dorado.web.DoradoContext;

@Component("tcpjjhceqsPR")
public class TcpjjhceqsPR {

	private Integer PZ_CODE_ = 5;
	private static final Integer Font_Size = 16;

	@Resource
	@Autowired
	private TcpjjhceqsDao tcpjjhceqsDao;

	@Transactional
	@DataProvider
	public Record getTcpjjhceqss() {
		try {
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				return null;
			if (loginuser.getDepts() == null
					|| loginuser.getDepts().size() <= 0)
				return null;

			Record record = new Record();
			record.put("pzdate", new Date());
			Collection<HcTcpjjhceqs> lists = tcpjjhceqsDao.getMuByDeptName();
			if (lists.isEmpty()) {
				HcTcpjjhceqs e = new HcTcpjjhceqs();
				e.setPzDate(new Date());
				e.setPzTemplate("新建模板");
				lists.add(e);
				record.put("tcpjjhceqs", lists);
			} else {
				for (HcTcpjjhceqs tcp : lists) {
					tcp.setPzDate(new Date());
				}
				record.put("tcpjjhceqs", lists);
			}

			List<HcpzXY> tcpjjhceqsXYs = tcpjjhceqsDao
					.getHcTcpjjhceqsXYs(PZ_CODE_);
			if (tcpjjhceqsXYs != null && !tcpjjhceqsXYs.isEmpty()) {
				record.put("pys", tcpjjhceqsXYs);
			} else {
				tcpjjhceqsXYs = new ArrayList<HcpzXY>();
				HcpzXY tcpjjhceqsXY = new HcpzXY();

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("页边距", 50, 50, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setId(UUID.randomUUID().toString());
				tcpjjhceqsXY.setProperty("年", 280, 68, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("月", 350, 68, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("日", 400, 68, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				// tcpjjhceqsXY = new HcpzXY();
				// tcpjjhceqsXY.setProperty("流水号", 560, 68);
				// tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("附件数量", 704, 245, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("清算行账号", 175, 158, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("清算行名称", 175, 108, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("小写金额", 688, 230, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("大写金额", 160, 205, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("清算行交换号", 480, 273, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("交换场次", 480, 329, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

				tcpjjhceqsXY = new HcpzXY();
				tcpjjhceqsXY.setProperty("借贷标记", 526, 381, Font_Size);
				tcpjjhceqsXYs.add(tcpjjhceqsXY);

			}
			record.put("pys", tcpjjhceqsXYs);

			return record;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	private void setImageData(Graphics2D graphics, Map<String, Object> param) {
		try {
			HcTcpjjhceqs tcpjjhceqs = (HcTcpjjhceqs) param.get("tcpjjhceqs");
			Date pzdate = (Date) param.get("pzdate");

			String cnFont = param.get("cnFont").toString();
			String numFont = param.get("numFont").toString();

			int pyx = (int) Integer.parseInt(param.get("x").toString());
			int pyy = (int) Integer.parseInt(param.get("y").toString());

			graphics.setBackground(Color.WHITE);
			graphics.setColor(Color.BLACK);
			// Font zhFont = new Font(cnFont, Font.PLAIN, size);
			// Font enFont = new Font(numFont, Font.PLAIN,size );

			List<HcpzXY> hctcpjjhceqs = (List<HcpzXY>) param.get("pys");

			for (HcpzXY pym : hctcpjjhceqs) {

				int x = pym.getX() + pyx;
				int y = pym.getY() + pyy;
				int size = pym.getFontSize();
				String lable = pym.getLabel();
				// System.out.println(lable);
				if (pzdate != null) {
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(pzdate);

					if (lable.equals("年")) {
						Font enFont = new Font(numFont, Font.PLAIN, size);
						graphics.setFont(enFont);
						graphics.drawString(
								String.format("%04d",
										calendar.get(Calendar.YEAR)), x, y);
					}
					if (lable.equals("月")) {
						Font enFont = new Font(numFont, Font.PLAIN, size);
						graphics.setFont(enFont);
						graphics.drawString(
								String.format("%02d",
										calendar.get(Calendar.MONTH) + 1), x, y);
					}
					if (lable.equals("日")) {
						Font enFont = new Font(numFont, Font.PLAIN, size);
						graphics.setFont(enFont);
						graphics.drawString(
								String.format("%02d",
										calendar.get(Calendar.DATE)), x, y);
					}

				}
				if (hctcpjjhceqs != null) {
					// if (lable.equals("流水号")) {
					// if (tcpjjhceqs.getSerialnumber() != null) {
					// graphics.setFont(enFont);
					// graphics.drawString(tcpjjhceqs.getSerialnumber(),
					// x, y);
					// }
					//
					// }
					if (lable.equals("附件数量")) {
						if (tcpjjhceqs.getAttachmentCount() != null) {
							Font enFont = new Font(numFont, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(String.valueOf(tcpjjhceqs
									.getAttachmentCount()), x - 5, y);
						}
					}
					if (lable.equals("清算行名称")) {
						if (tcpjjhceqs.getQsName() != null) {
							Font zhFont = new Font(cnFont, Font.PLAIN, size);
							graphics.setFont(zhFont);
							graphics.drawString(tcpjjhceqs.getQsName(), x, y);
						}
					}
					if (lable.equals("清算行账号")) {
						if (tcpjjhceqs.getQsUsername() != null) {
							Font enFont = new Font(numFont, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(tcpjjhceqs.getQsUsername(), x,
									y);
						}
					}

					if (lable.equals("小写金额")) {
						if (tcpjjhceqs.getAmountNum() != null) {
							Font enFont = new Font(numFont, Font.PLAIN, size);
							graphics.setFont(enFont);
							DecimalFormat df = new DecimalFormat(".00");
							char[] chars;
							int endX = x;
							if (tcpjjhceqs.getIssign() == 0) {
								chars = ("¥" + df.format(
										tcpjjhceqs.getAmountNum()).replace(".",
										"")).toCharArray();

								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i
											- 1]
											+ "", endX - i * 15 - i / 5 - 4,
											y - 5);
								}

							}
							if (tcpjjhceqs.getIssign() == 1) {
								chars = ("HKD" + df.format(
										tcpjjhceqs.getAmountNum()).replace(".",
										"")).toCharArray();

								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i
											- 1]
											+ "", endX - i * 15 - i / 5 - 4,
											y - 5);
								}

							}
							if (tcpjjhceqs.getIssign() == 2) {
								chars = ("USD" + df.format(
										tcpjjhceqs.getAmountNum()).replace(".",
										"")).toCharArray();

								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i
											- 1]
											+ "", endX - i * 15 - i / 5 - 4,
											y - 5);
								}

							}
							if (tcpjjhceqs.getIssign() == 3) {
								chars = (df.format(tcpjjhceqs.getAmountNum())
										.replace(".", "")).toCharArray();

								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i
											- 1]
											+ "", endX - i * 15 - i / 5 - 4,
											y - 5);
								}
							}
						}
					}
					if (lable.equals("大写金额")) {
						Font zhFont = new Font(cnFont, Font.PLAIN, size);
						graphics.setFont(zhFont);
						int rowcount = 18;
						if(tcpjjhceqs.getAmountNum()==null){
							return;
						}
						if (tcpjjhceqs.getIssign() == 0) {
							if (tcpjjhceqs.getAmountZh().length() > rowcount) {
								graphics.drawString(tcpjjhceqs.getAmountZh()
										.substring(0, rowcount), x, y);
								graphics.drawString(tcpjjhceqs.getAmountZh()
										.substring(rowcount), x, 20 + y);
							} else {
								graphics.drawString(tcpjjhceqs.getAmountZh(),
										x, 10 + y);
							}
						}
						if (tcpjjhceqs.getIssign() == 1) {
							if (tcpjjhceqs.getAmountZh().length() > rowcount) {
								graphics.drawString(
										"港币    "
												+ tcpjjhceqs.getAmountZh()
														.substring(0, rowcount),
										x - 50, y);
								graphics.drawString(tcpjjhceqs.getAmountZh()
										.substring(rowcount), x, 20 + y);
							} else {
								graphics.drawString(
										"港币    " + tcpjjhceqs.getAmountZh(),
										x - 50, y);
							}
						}
						if (tcpjjhceqs.getIssign() == 2) {
							if (tcpjjhceqs.getAmountZh().length() > rowcount) {
								graphics.drawString(
										"美元   "
												+ tcpjjhceqs.getAmountZh()
														.substring(0, rowcount),
										x - 50, y);
								graphics.drawString(tcpjjhceqs.getAmountZh()
										.substring(rowcount), x, 20 + y);
							} else {
								graphics.drawString(
										"美元   " + tcpjjhceqs.getAmountZh(),
										x - 50, y);
							}
						}
						if (tcpjjhceqs.getIssign() == 3) {
							if (tcpjjhceqs.getAmountZh().length() > rowcount) {
								graphics.drawString(tcpjjhceqs.getAmountZh()
										.substring(0, rowcount), x, y);
								graphics.drawString(tcpjjhceqs.getAmountZh()
										.substring(rowcount), x, 20 + y);
							} else {
								graphics.drawString(tcpjjhceqs.getAmountZh(),
										x, 10 + y);
							}
						}
					}
					if (lable.equals("清算行交换号")) {
						if (tcpjjhceqs.getQsDealNumber() != null) {
							Font enFont = new Font(numFont, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(tcpjjhceqs.getQsDealNumber()
									+ "", x, y - 2);
						}
					}
					if (lable.equals("交换场次")) {
						if (tcpjjhceqs.getDealNum() != null) {
							Font enFont = new Font(numFont, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(tcpjjhceqs.getDealNum() + "",
									x, y - 5);
						}
					}

					if (lable.equals("借贷标记")) {
						if (tcpjjhceqs.getLendTag() != null) {
							Font zhFont = new Font(cnFont, Font.PLAIN, size);
							graphics.setFont(zhFont);
							String click = "√";
							if (Integer.parseInt(tcpjjhceqs.getLendTag()) == 0) {
								graphics.drawString(click, x - 8, y - 6);
							}
							if (Integer.parseInt(tcpjjhceqs.getLendTag()) == 1) {
								graphics.drawString(click, x + 77, y - 6);
							}
							if (Integer.parseInt(tcpjjhceqs.getLendTag()) == 2) {

							}
						}

					}
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@Expose
	public String getPrintImageAll(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", 0);
			param.put("y", 0);
			BufferedImage imagepz = ImageIO.read(new File(DoradoContext
					.getCurrent().getServletContext()
					.getRealPath("pz/tcpjjhceqs.jpg")));
			Graphics2D graphicspz = (Graphics2D) imagepz.getGraphics();
			setImageData(graphicspz, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/all_" + loginuser.getUsername() + ".jpg";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext
					.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagepz, "jpg", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public String getPrintImageData(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", -34);
			param.put("y", -40);
			BufferedImage imagedata = ImageIO.read(new File(DoradoContext
					.getCurrent().getServletContext()
					.getRealPath("pz/tcpjjhceqs.jpg")));
			// System.out.println(imagepz.getWidth()*1.0/96.0*24.5);
			// BufferedImage imagedata= new BufferedImage(imagepz.getWidth(),
			// imagepz.getHeight(), imagepz.getType());
			Graphics2D graphicsdata = (Graphics2D) imagedata.getGraphics();
			graphicsdata.setBackground(Color.WHITE);

			// 打印背景图片
			graphicsdata.clearRect(0, 0, imagedata.getWidth(),
					imagedata.getHeight());
			setImageData(graphicsdata, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/data_" + loginuser.getUsername()
					+ ".jpg";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext
					.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagedata, "jpg", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public Map<String, Object> getUserInfo() {
		IUser loginuser = ContextHolder.getLoginUser();
		Map<String, Object> userinfo = new HashMap<String, Object>();
		if (loginuser == null) {
			userinfo.put("cname", "");
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("cname", loginuser.getCname());
		if (loginuser.getDepts() == null || loginuser.getDepts().size() <= 0) {
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("dept", loginuser.getDepts().get(0).getName());
		return userinfo;
	}

	@DataProvider
	public Collection<HcTcpjjhceqs> getTypeByGroup() {
		return tcpjjhceqsDao.getOneGroupByType();

	}

	@SuppressWarnings("unused")
	@DataProvider
	public Collection<HcTcpjjhceqs> getTepementNameByType(
			Map<String, Object> param) {
		if (param == null) {
			return null;
		}
		String type = (String) param.get("type");
		return tcpjjhceqsDao.getCoByType(type);
	}

	@Expose
	public HcTcpjjhceqs ajaxselectOneByTypeAndTemplate(Map<String, Object> param) {
		String type = (String) param.get("type");
		String pzTemplate = (String) param.get("pzTemplate");
		if (type == null || pzTemplate == null) {
			return null;
		}
		return tcpjjhceqsDao.selectOneByTypeAndTemplate(type, pzTemplate);

	}

	@DataProvider
	public List<Record> getFonts() {
		return tcpjjhceqsDao.getFonts();

	}

	@DataProvider
	public PzFont getFont() {
		return tcpjjhceqsDao.getFont(PZ_CODE_);
	}

	@Transactional
	@DataResolver
	public void saveTcpjjhceqs(HcTcpjjhceqs tcpjjhceqs) {
		tcpjjhceqsDao.saveTcpjjhceqs(tcpjjhceqs);
	}

	@Transactional
	@DataResolver
	public void saveTcpjjhceqsXY(Collection<HcpzXY> tcpjjhceqs) {
		tcpjjhceqsDao.saveTcpjjhceqsXY(tcpjjhceqs);

	}

	@Transactional
	@DataResolver
	public void saveFont(PzFont pzFont) throws Exception {
		tcpjjhceqsDao.updateFont(pzFont);
	}

	@Expose
	public void deleteTemplateById(String id) {
		if (StringUtils.isEmpty(id)) {
			return;
		}
		tcpjjhceqsDao.deleteTemplateById1(id);

	}

	@Expose
	public String getQsNameByQsUserName(String qsUsername) {
		return tcpjjhceqsDao.getQsNameByQsUsername(qsUsername);
	}

	@Expose
	public boolean updateTemplateNameDao(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String pzTemplate = (String) parameter.get("pzTemplate");
		return tcpjjhceqsDao.updateTemplateNameDao(pzTemplate, id);
	}

	@Expose
	public boolean updateTemplateTypeDao(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String type = (String) parameter.get("type");
		return tcpjjhceqsDao.updateTemplateTypeDao(type, id);
	}

}